import React, { useState } from "react";
import SearchForm from "@/components/searchForm";
import { Table, Divider, Button, message, Modal, Badge, Tag } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { dataSourceAdd, dataSourcePage, dataSourceUpdate, dataSourceTestConnection, dataSourceDelete } from '@/api/sharing/dataSource'
import DataSourceForm from "./modules/DataSourceForm";
const queryItems = [
  {
    name: 'keyword',
    label: '数据源名称',
    type: 'INPUT',
  },
  {
    name: 'dataSourceType',
    label: '数据源类型',
    type: 'SELECT',
    dictType: 'data_source_type'
  }
];
//i18n
const DataSourceIndex = () => {
  useDictionary(['data_source_type']);
  const [queryParam, setQueryParam] = useState({});
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = React.useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '数据源名称',
      dataIndex: 'dataSourceName',
    },
    {
      title: '数据源类型',
      dataIndex: 'dataSourceType',
      render: (text) => (<Tag><DisplayLabel value={text} type="data_source_type" /></Tag>)
    },
    {
      title: '主机IP',
      dataIndex: 'hostIp',
    },
    {
      title: '端口',
      dataIndex: 'port',
    },
    {
      title: '数据库名',
      dataIndex: 'databaseName',
    },
    {
      title: '描述',
      dataIndex: 'describe',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '160px',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改-` + record.dataSourceName}
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <DataSourceForm />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { handleTestConnection(record) }}>测试</a>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-DataSourceIndex-dataSourcePage', page, queryParam],
    queryFn: () => {
      return dataSourcePage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam,
      }).then((res) => {
        return res?.result || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const handleSave = (values) => {
    if (values.id) {
      return dataSourceUpdate(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return dataSourceAdd(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = [row.id] || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return dataSourceDelete(ids)
          .then((res) => {
            if (res.code === 200) {
              onSelectChange([], [])
              refetch()
              message.success('删除成功')
            }
          })
      },
      onCancel() { },
    });
  };

  const handleTestConnection = (row) => {
    dataSourceTestConnection(row).then((res) => {
      if (res.code === 200) {
        message.success('连接成功')
      }
    })
  }

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">数据源管理</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
            setQueryParam({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        buttons={<>
          <ModalForm
            trigger={<Button className="ml-2" icon={<PlusOutlined />} type="primary">新增</Button>}
            title="新增数据源"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            grid={true}
            initialValues={{
              status: '0'
            }}
          >
            <DataSourceForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.records}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
    </div>
  );
};


export default DataSourceIndex;
